#!/usr/bin/python

from PySide.QtGui import QPixmap
from PySide.QtCore import Qt, QUrl, QAbstractListModel, QModelIndex
from PySide.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest

class VideoListModel(QAbstractListModel):
    def __init__(self, data, parent=None, *args):
        QAbstractListModel.__init__(self, parent, *args)
        self.videolist_data = data
        self.thumbnails = {}
        self.nothumbnail = QPixmap('nothumbnail.jpg')

        self.networkManager = QNetworkAccessManager(self)
        self.networkManager.finished.connect(self.networkManagerFinished_cb)

    def networkManagerFinished_cb(self, reply):
        uri = str(reply.url().toString())
        if reply.error() != QNetworkReply.NoError:
            print 'Error in ' + uri + ' : ' + reply.errorString()
            return
        jpegData = reply.readAll()
        pixmap = QPixmap()
        pixmap.loadFromData(jpegData)
        self.thumbnails[uri] = pixmap
        self.layoutChanged.emit()

    def rowCount(self, parent=QModelIndex()):
        return len(self.videolist_data)

    def data(self, index, role):
        if index.isValid() and role == Qt.DisplayRole:
            video_entry = self.getVideoEntry(index)
            duration = '%d:%d' % (video_entry.duration_seconds / 60,
                                  video_entry.duration_seconds % 60)
            return video_entry.title + '\n\n' + video_entry.description + '\nDuration: ' + duration
        elif index.isValid() and role == Qt.DecorationRole:
            uri = self.getVideoEntry(index).thumbnails[0]
            if not uri in self.thumbnails:
                self.thumbnails[uri] = self.nothumbnail
                self.networkManager.get(QNetworkRequest(QUrl(uri)))
            return self.thumbnails[uri]
        return None

    def getVideoEntry(self, index):
        return self.videolist_data[index.row()]


class PlaylistModel(QAbstractListModel):
    def __init__(self, data, parent=None, *args):
        QAbstractListModel.__init__(self, parent, *args)
        self.playlist_data = data
        self.videolist_models = {}

    def rowCount(self, parent=QModelIndex()):
        return len(self.playlist_data)

    def data(self, index, role):
        if index.isValid() and role == Qt.DisplayRole:
            return self.playlist_data[index.row()].name
        return None

    def getPlaylistEntry(self, index):
        return self.playlist_data[index.row()]

    def getVideoListModel(self, index):
        if not index.isValid():
            return None
        if index.row() not in self.videolist_models:
            playlist = self.getPlaylistEntry(index)
            if not playlist.video_entries:
                playlist.load_video_entries()
            model = VideoListModel(playlist.video_entries)
            self.videolist_models[index.row()] = model
        return self.videolist_models[index.row()]


